package online.afeibaili.storebackendframework

import online.afeibaili.storebackendframework.util.saveProductImage
import java.io.File
import kotlin.test.Test


/**
 * 存储产品
 *
 *@author AfeiBaili
 *@version 2025/11/14 00:50
 */

val flowerDirectory = File("C:\\Users\\AfeiB\\Desktop\\flower")

class SaveProduct {

    @Test
    fun save() {
        flowerDirectory.listFiles().forEach {
            val details: ProductDetails = readProductDirectory(it)
        }
    }
}

fun readProductDirectory(file: File): ProductDetails {
    val files: Array<File> = file.listFiles()

    var images: List<String>
    var title: String? = null
    var materials: List<String> = emptyList()
    var flowerSay: String? = null
    var tag: List<String> = emptyList()
    var price: Int? = null
    var normalPrice: Int? = null

    var fileNewName: String? = null
    var imageFiles: List<File> = listOf()
    files.forEach { typeFile ->
        when (typeFile.name) {
            //文件夹拼错...
            "iamge" -> {
                imageFiles = typeFile.listFiles().toList()
            }

            "标题.txt" -> {
                title = typeFile.readText(Charsets.UTF_8).replace("\\s".toRegex(), "")
                fileNewName = "【(.+)】".toRegex().find(title!!)!!.groupValues[1]
            }

            "材料.txt" -> {
                val materialsText: String = typeFile.readText(Charsets.UTF_8).replace("\\s".toRegex(), "")
                materials = materialsText.split("+").toList()
            }

            "花语.txt" -> {
                flowerSay = typeFile.readText(Charsets.UTF_8).replace("\\s".toRegex(), "")
            }

            "适用对象.txt" -> {
                val tagText: String = typeFile.readText(Charsets.UTF_8).replace("\\s".toRegex(), "")
                tag = tagText.split("[/、]".toRegex()).toList()
            }

            else -> {
                if (price == null) {
                    price = typeFile.name.toInt()
                } else {
                    normalPrice = typeFile.name.toInt()
                    if (normalPrice!! < price!!) {
                        val tempValue = normalPrice
                        normalPrice = price
                        price = tempValue
                    }
                }
            }
        }
    }

    val listOf = mutableListOf<String>()
    imageFiles.forEachIndexed { index, file ->
        listOf += saveProductImage(file)
    }

    images = listOf

    file.renameTo(
        File(
            flowerDirectory.path + "/" + fileNewName + "-" + System.currentTimeMillis().toString()
        )
    )

    return ProductDetails(images, price!!, normalPrice!!, title!!, materials, flowerSay!!, tag)
}

data class ProductDetails(
    val images: List<String>,
    val price: Int,
    val normalPrice: Int,
    val title: String,
    val materials: List<String>,
    val flowerSay: String,
    val tag: List<String>,
)